/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.fill;

import com.wtkj.vo.dzzf.base.kfwd.OBU;
import com.wtkj.vo.dzzf.base.kfzx.ObuGoods;
import com.wttech.dzzf.process.dao.FillMissingDataDao;
import com.wttech.dzzf.process.dao.TransferUserInfoDao;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import com.wttech.dzzf.process.util.BusinessUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import static com.wttech.dzzf.process.constant.UserConstants.DEFAULT_PROCESS_NUM;

/**
 * 填充OBU相关信息
 *
 * @author MaShibo
 * @date 2017/12/11.
 */
@Service
public class FillObuInfosService {

	private static final Logger LOGGER = LoggerFactory.getLogger(FillObuInfosService.class);

	@Resource
	private BaseInfoService baseInfoService;

	@Resource
	private FillMissingDataDao fillMissingDataDao;

	@Resource
	private TransferUserInfoDao transferUserInfoDao;

	@Resource
	private ThreadPoolTaskExecutor executor;

	void fill() {
		while (true) {
			List<OBU> obus = fillMissingDataDao.queryMissingInfoObus(DEFAULT_PROCESS_NUM);
			if (CollectionUtils.isEmpty(obus)){
				LOGGER.info("OBU信息填充完毕");
				return;
			}
			List<Future<Void>> futures = new ArrayList<>(obus.size());
			LOGGER.info("开始填充OBU信息");
			obus.forEach(obu -> futures.add(executor.submit(() -> {
				fillObu(obu);
				return null;
			})));
			baseInfoService.getFutureResult(futures);
		}
	}

	private void fillObu(OBU obu) {
		try {
			String obuNo = obu.getObuNo();
			Object goodsIdObj = obu.getExtendProperties().get("GOODSID");
			if (goodsIdObj == null) {
				LOGGER.info("OBU编号【{}】没有对应的入库记录", obuNo);
				return;
			}
			String goodsId = goodsIdObj.toString();
			ObuGoods update = new ObuGoods();

			Integer brand = BusinessUtils.determineObuBrand(obu.getObuId(), obuNo);
			String model = BusinessUtils.determineObuModel(brand, obuNo);

			update.setId(goodsId);
			update.setBrand(brand);
			update.setModel(model);
			transferUserInfoDao.updateDzzfObject(update);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}

}
